MATLAB 查找文件夹(包括子文件夹)下特定类型的文件

简介

在对文件查找,遍历等操作时,经常遇到对文件夹下所有的特地类型文件汇总或者遍历等批量操作,首先就需要对文件夹下或者文件夹下包含的子文件夹下的文件全部收集,采用下面提供的函数即可:

函数

函数输入为:需要搜索的路径,需要搜索的文件扩展名(可同时对多种扩展名搜索)
例如:
ListPath = folder_search( pwd, {‘m’,‘p’})
即对当前文件夹下的m类型和p类型的文件搜索,并将搜索到的文件完整路径都放置在ListPath 这个cell数组变量中。
也可以对单个文件类型搜索,例如:
ListPath = folder_search( pwd, ‘m’)

源代码

% 搜索路径
function ListPath = folder_search( path_target, extension_target )
list_dir = dir( path_target );
ListPath = {  };
for i = 1:1:length( list_dir )
    if isdir( fullfile( path_target, list_dir( i ).name ) ) && ~strcmp( list_dir( i ).name, '.' ) && ~strcmp( list_dir( i ).name, '..' )
        ListPathSub = folder_search( fullfile(path_target, list_dir( i ).name), extension_target );
        if ~isempty( ListPathSub )
            ListPath = [ ListPath;ListPathSub ];
        end
    else
        idx_dot = regexp( list_dir( i ).name, '\.' );
        file_extension = list_dir( i ).name( ( idx_dot( end  ) + 1 ):end  );
        if ~isempty( find( strcmp( file_extension, extension_target ) ) )
            ListPath = [ ListPath;fullfile( path_target, list_dir( i ).name ) ];
        end
    end
end
end
  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值